import pandas as pd  # 存入excel数据
import requests  # 向页面发送请求
from bs4 import BeautifulSoup as BS  # 解析页面

# 目标地址
url = 'https://s.weibo.com/top/summary?cate=realtimehot'

# 请求头（需将 Cookie 替换为你自己的）
header = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Mobile Safari/537.36',
    'Host': 's.weibo.com',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br',
    'Cookie': 'SCF=AkQfArcuTWEVHm97eC8sq7vUZEYUI2Iupm4wki864YWxdFtLS2HH2Y7wxukYVzoCluLOXlkx9x-3cjh8ui9bPTY.; SINAGLOBAL=7598969540847.758.1732000341034; PC_TOKEN=fcb3398d8a; ALF=1735223666; SUB=_2A25KQawiDeRhGeBI61UW8S3LyzyIHXVpPqHqrDV8PUJbkNANLRnbkW1NRrmFp41xgQUqtKLxotAkT2eN1U89XGVj; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFO0bn4W0Es7DV2hb5BkuXW5JpX5KMhUgL.FoqcehMNeKeNeh52dJLoI0qLxKML1hnLBo2LxK-L1KqL1-BLxKML1K.LB.BLxK-LB.eL1h5LxKqLBo5LBoBLxK-L1KMLBoMt; _s_tentry=-; Apache=9094094674618.266.1732631697891; ULV=1732631698062:3:3:1:9094094674618.266.1732631697891:1732008404792'
}

def trans_icon(v_str):
    """转换热搜类别"""
    if v_str == 'icon_new':
        return '新'
    elif v_str == 'icon_hot':
        return '热'
    elif v_str == 'icon_boil':
        return '沸'
    elif v_str == 'icon_recommend':
        return '商'
    else:
        return '未知'

r = requests.get(url, headers=header)  # 发送请求
soup = BS(r.text, 'html.parser')

text_list = []
order_list = []
type_list = []
view_count_list = []
href_list = []

items = soup.find('section', {'class': 'list'})
for li in items.find_all('li'):
    # 热搜标题
    text = li.find('a').text
    text_list.append(text)
    # 热搜排名（如果存在）
    rank_elem = li.find('td', {'class': 'td-01'})
    if rank_elem is not None:
        order = rank_elem.text
    else:
        order = '置顶'
    order_list.append(order)

    # 热搜类型（假设类型在某个类名中）
    type_elem = li.find('span', {'class': 'icon'})  # 假设类型在这个类中
    if type_elem is not None:
        type_list.append(trans_icon(type_elem['class'][0]))  # 将类名转换为中文
    else:
        type_list.append('未知')

        # 观看次数（假设在某个类名中）
    view_count_elem = li.find('span', {'class': 'count'})  # 假设观看次数在这个类中
    if view_count_elem is not None:
        view_count_list.append(view_count_elem.text)
    else:
        view_count_list.append('未知')

        # 热搜链接
    href = li.find('a')['href']
    href_list.append(href)

    # 创建 DataFrame
data = {import pandas as pd  # 存入excel数据
import requests  # 向页面发送请求
from bs4 import BeautifulSoup as BS  # 解析页面

# 目标地址
url = 'https://s.weibo.com/top/summary?cate=realtimehot'

# 请求头（需将 Cookie 替换为你自己的）
header = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Mobile Safari/537.36',
    'Host': 's.weibo.com',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br',
    'Cookie': 'SCF=AkQfArcuTWEVHm97eC8sq7vUZEYUI2Iupm4wki864YWxdFtLS2HH2Y7wxukYVzoCluLOXlkx9x-3cjh8ui9bPTY.; SINAGLOBAL=7598969540847.758.1732000341034; PC_TOKEN=fcb3398d8a; ALF=1735223666; SUB=_2A25KQawiDeRhGeBI61UW8S3LyzyIHXVpPqHqrDV8PUJbkNANLRnbkW1NRrmFp41xgQUqtKLxotAkT2eN1U89XGVj; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFO0bn4W0Es7DV2hb5BkuXW5JpX5KMhUgL.FoqcehMNeKeNeh52dJLoI0qLxKML1hnLBo2LxK-L1KqL1-BLxKML1K.LB.BLxK-LB.eL1h5LxKqLBo5LBoBLxK-L1KMLBoMt; _s_tentry=-; Apache=9094094674618.266.1732631697891; ULV=1732631698062:3:3:1:9094094674618.266.1732631697891:1732008404792'
}

def trans_icon(v_str):
    """转换热搜类别"""
    if v_str == 'icon_new':
        return '新'
    elif v_str == 'icon_hot':
        return '热'
    elif v_str == 'icon_boil':
        return '沸'
    elif v_str == 'icon_recommend':
        return '商'
    else:
        return '未知'

r = requests.get(url, headers=header)  # 发送请求
soup = BS(r.text, 'html.parser')

text_list = []
order_list = []
type_list = []
view_count_list = []
href_list = []

items = soup.find('section', {'class': 'list'})
for li in items.find_all('li'):
    # 热搜标题
    text = li.find('a').text
    text_list.append(text)
    # 热搜排名（如果存在）
    rank_elem = li.find('td', {'class': 'td-01'})
    if rank_elem is not None:
        order = rank_elem.text
    else:
        order = '置顶'
    order_list.append(order)

    # 热搜类型（假设类型在某个类名中）
    type_elem = li.find('span', {'class': 'icon'})  # 假设类型在这个类中
    if type_elem is not None:
        type_list.append(trans_icon(type_elem['class'][0]))  # 将类名转换为中文
    else:
        type_list.append('未知')

        # 观看次数（假设在某个类名中）
    view_count_elem = li.find('span', {'class': 'count'})  # 假设观看次数在这个类中
    if view_count_elem is not None:
        view_count_list.append(view_count_elem.text)
    else:
        view_count_list.append('未知')

        # 热搜链接
    href = li.find('a')['href']
    href_list.append(href)

    # 创建 DataFrame
data = {
    '排名': order_list,
    '热搜标题': text_list,
    '类型': type_list,
    '观看次数': view_count_list,
    '链接': href_list
}

df = pd.DataFrame(data)

# 保存为 Excel 文件
file_path = r"C:\Users\卷\Desktop\新建文件夹\新建 Microsoft Excel 工作表.xlsx"
df.to_excel(file_path, index=False)  # 保存为指定路径的 Excel 文件

# 或者保存为 CSV 文件
# df.to_csv('微博热搜.csv', index=False, encoding='utf-8-sig')  # 如需保存为 CSV 文件
    '排名': order_list,
    '热搜标题': text_list,
    '类型': type_list,
    '观看次数': view_count_list,
    '链接': href_list
}

df = pd.DataFrame(data)

# 保存为 Excel 文件
file_path = r"C:\Users\卷\Desktop\新建文件夹\新建 Microsoft Excel 工作表.xlsx"
df.to_excel(file_path, index=False)  # 保存为指定路径的 Excel 文件

# 或者保存为 CSV 文件
# df.to_csv('微博热搜.csv', index=False, encoding='utf-8-sig')  # 如需保存为 CSV 文件